package com.bye.intercept;

import com.bye.annotation.Login;
import com.bye.exception.MyException;
import com.bye.util.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
public class AuthIntercept implements HandlerInterceptor {
    @Autowired
    private JwtUtils jwtUtils;
    //每次请求前, 执行该方法
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //定义变量注解
        Login anno;

        //判断当前请求是否是一个接口方法
        if (handler instanceof HandlerMethod) {
            //获取方法上的login注解
            anno = ((HandlerMethod)handler).getMethodAnnotation(Login.class);

        }else {
            return true;
        }
        //如果anno为空,代表没有获取到方法上的login注解, 也就是说方法没有被login修饰
        //也就代表不需要登录验证
        if (anno == null){
            return true;
        }

        String token = request.getHeader("token");
        if (token != null && !"".equals(token)) {
            try {
                Claims tokenBody = jwtUtils.getTokenBody(token);
                String manager = tokenBody.getSubject();
                request.setAttribute("manager",manager);
            }catch (Exception e){
                throw new MyException("登录已失效, 请重新登录");
            }
        }else {
            throw new MyException("未登录, 请重新登录");
        }
        return true;
    }
}
